from weibo import *  
import webbrowser

def new_post(client, msg):
    """
    Function to send a new post
    """  
    try:
        client.statuses.update.post(status=msg)
    except Exception, e:
        print e
        print "Error when posting"


def show_friends(client, _uid):
    """
    Function for showing your watching list
    """
    try:
        users = client.friendships.friends.get(uid = _uid )["users"]
        for user in users:
            print  " " + user["screen_name"], "(" + str(user["id"]) + ")"

    except Exception, e:
        print e
        print "Error when reading friend list"


def show_mypost(client, _uid):
    """
    Function for showing my posts
    """
    try:
        posts = client.statuses.user_timeline.get(uid = _uid)["statuses"]
        print_posts(posts, "I")
    except Exception, e:
        print e
        print "Error when reading my posts"


def show_timeline(client):
    """
    Function for showing the timeline
    """
    try:
        posts = client.statuses.friends_timeline.get()["statuses"]
        print_posts(posts)
    except Exception, e:
        print e
        print "Error when reading the timeline"
        
def print_posts(posts, who = None):
    """
    Helper function to print all the posts
    """
    for post in posts:
        try:
            if who == None:
                print post["user"]["screen_name"], "said", "(" + str(post["id"]) + ")"
            else:
                print who, "said", "(" + str(post["id"]) + ")"
            print "\t", post["text"]
            print "\n"
        except Exception, e:
            pass

def do_comment(client, _id, _comment):
    try:
        client.comments.create.post(id = _id, comment = _comment)
    except Exception, e:
        print e
        print "Error when commenting"


def post_with_pic(client, msg, pic_path):
    try:
        client.statuses.upload.post(status = msg, pic = open(pic_path,"rb"))
        # Be careful with the rb mode when opening
    except Exception, e:
        print e
        print "Error when posting with pictures"


if __name__ == '__main__': 

    for i in range(100):
        print ""

    APP_KEY = '3393803453'  
    APP_SECRET = 'c0493aec3a795f02d2ea28a20f27f363'  

    CALLBACK_URL = 'https://api.weibo.com/oauth2/default.html'
      
    client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=CALLBACK_URL)  
    url =  client.get_authorize_url()


    print "If you redirect to https://api.weibo.com/oauth2/default.html?code=[code]"
    print "Please input the [code] here\n"
    raw_input("Press enter to continue ...")

    
    webbrowser.open(url)
    
    r = client.request_access_token(raw_input("input code:").strip())
    client.set_access_token(r.access_token, r.expires_in)  

    uid = client.account.get_uid.get()["uid"]

    #show_friends(client, uid) # OK
    #show_timeline(client) # OK
    #show_mypost(client, uid)
    while True:
        print """
        --------------------
        Options:
        1. Send a new post
        2. Show your timeline
        3. Show your posts
        4. Show your friends
        5. Do some comment
        6. Post with pictures
        0. Exit
        --------------------
        """

        option = int(raw_input("> "))
        if option == 1:
            msg = raw_input("Your new post in one line~:\n")
            new_post(client, msg)
        elif option == 2:
            show_timeline(client)
        elif option == 3:
            show_mypost(client, uid)
        elif option == 4:
            show_friends(client, uid)
        elif option == 5:
            weibo_id = int(raw_input("Which weibo to comment: "))
            comment = raw_input("Comment in one line: ")
            do_comment(client, weibo_id, comment)
        elif option == 6:
            pic = raw_input("Picture path>")
            msg = raw_input("Your new post in one line~:\n")
            post_with_pic(client, msg, pic)
        elif option == 0:
            break

